package com.itheima.mall.sso.api;

import com.itheima.mall.commons.utils.StringUtils;
import com.itheima.mall.commons.utils.redis.JwtUtils;
import com.itheima.mall.commons.utils.redis.RedisCache;
import com.itheima.mall.sso.mapper.UserMapper;
import com.itheima.mall.sso.pojo.LoginUser;
import io.jsonwebtoken.Claims;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.concurrent.TimeUnit;

@DubboService
public class SsoServiceImpl implements SsoService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisCache redisCache;

    @Override
    public LoginUser login(LoginUser loginUser) {
        LoginUser user = userMapper.getByName(loginUser.getUsername());
        if (user != null) {
            String jwt = JwtUtils.createJWT(String.valueOf(user.getId()), user.getUsername(), 10000000L);
            redisCache.setCacheObject(jwt, user, 60, TimeUnit.MINUTES);
            user.setToken(jwt);
            return user;
        } else {
            return null;
        }
    }

    @Override
    public LoginUser checkToken(String token) {
        if (StringUtils.isBlank(token)) {
            return null;
        }

        LoginUser user = redisCache.getCacheObject(token);
        if (user != null) {
            return user;
        } else {
            return null;
        }
    }

    @Override
    public String parseToken(String token) {
        try {
            Claims claims = JwtUtils.parseJWT(token);
            String subject = claims.getSubject();
            return subject;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
